// pages/car/carIndex.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cars: [],
    total: 0,
    selectedAllStatus: true,
    minusStatuses: "disabled",
    choosegoods: [], //实际选中商品,
    uid: '',
    level: '',
    sid: ''
  },
  jumpindex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 选择商品
  choose: function(e) {
    let that = this
    let index = parseInt(e.currentTarget.dataset.index);
    let selected = that.data.cars[index].selected;
    let cars = that.data.cars;
    // toggle
    cars[index].selected = !selected;
    if (cars.every(that.allSel)) {
      that.setData({
        selectedAllStatus: true,
      })
    } else {
      that.setData({
        selectedAllStatus: false,
      })
    }
    let choosegoods = [] //实际选中商品
    for (let item of cars) {
      if (item.selected) {
        choosegoods.push(item)
      }
    }
    console.log(choosegoods)
    that.setData({
      cars: cars,
      choosegoods: choosegoods
    });
    that.sum();
  },
  // 判断是否 全选
  allSel(e) {
    return e.selected
  },
  // 全选
  SelectAll: function() {
    // 环境中目前已选状态
    let selectedAllStatus = this.data.selectedAllStatus;
    // 取反操作
    selectedAllStatus = !selectedAllStatus;
    // 购物车数据，关键是处理selected值
    let cars = this.data.cars;
    // 遍历
    for (var i = 0; i < cars.length; i++) {
      cars[i].selected = selectedAllStatus;
    }
    this.setData({
      selectedAllStatus: selectedAllStatus,
      cars: cars
    });
    this.sum();
  },

  bindMinus: function(e) {
    let index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.cars[index].num; //商品数量
    var sum = this.data.cars[index].sum;
    let type = e.currentTarget.dataset.type;
    var price = this.data.cars[index].price;
    let id = e.currentTarget.dataset.id;
    let gid = e.currentTarget.dataset.gid;
    console.log(gid)
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num--;
    }
    // 购物车数据
    var cars = this.data.cars;
    cars[index].num = num;
    cars[index].sum = (num * price).toFixed(1);
    this.setData({
      cars: cars,
    });
    this.sum();
    wx.request({
      url: app.globalData.api + "savecartnum",
      data: {
        gid: gid,
        id: id,
        num: num,
        price: price,
        type: type
      },
      success: function(res) {
        console.log(res)
      },
    })
  },
  bindPlus: function(e) {
    let that = this
    let index = parseInt(e.currentTarget.dataset.index);
    let type = e.currentTarget.dataset.type;
    var num = that.data.cars[index].num; //商品数量
    var sum = that.data.cars[index].sum;
    var price = that.data.cars[index].price;
    let id = e.currentTarget.dataset.id;
    let gid = e.currentTarget.dataset.gid;
    console.log(e.currentTarget.dataset.gid)
   
    var cars = that.data.cars;
    // if (that.data.maxnum == false) {
    //   cars[index].num = num - 1;
    //   wx.showToast({
    //     title: '数量超过库存',
    //   })
    // } else {
      
    // }
    ++num;
    wx.request({
      url: app.globalData.api + "savecartnum",
      data: {
        gid: gid,
        id: id,
        num: num,
        price: price,
        type: type
      },
      success: function(res) {
        console.log(res)
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          num--;
        }else{
          cars[index].num = num;
          cars[index].sum = (num * price).toFixed(1);
          that.sum();
          that.setData({
            cars: cars,
          });
        }
      },
    })
  },
  // 总价计算
  sum() {
    let cars = this.data.cars;
    console.log(cars, '总价')
    let total = 0;
    for (let item of cars) {
      if (item.selected) {
        console.log(typeof(item.num))
        console.log(typeof (item.goods.price))
          total += Number(item.goods.price) * Number(item.num);
       
      }
    }
    console.log(total)
    this.setData({
      total: total.toFixed(2),
    })
  },
  // 删除
  delete: function(e) {
    let that = this
    let index = parseInt(e.currentTarget.dataset.index);
    let cars = that.data.cars;
    let array = [];
    let array2 = []
    for (let item of cars) {
      // 正向选择
      if (item.selected) {
        array2.push(item)
      } else if (!item.selected) {
        // 反向选择
        array.push(item)
      }
    }
    that.setData({
      cars: array
    })
    let idbox = []
    for (let item of array2) {
      idbox.push(item.id)
    }
    console.log(idbox)
    idbox = JSON.stringify(idbox)
    that.sum()
    console.log(idbox)
    wx.request({
      url: app.globalData.api + "delcart",
      data: {
        uid: that.data.uid,
        id: idbox
      },
      success: function(res) {
        console.log(res)
      },
    })
  },
  
  // 结算
  submit() {
    let that = this
    let good = [] //选中
    let good2 = [] //没选
    let carts = [] //总价参数
    let car = encodeURIComponent(JSON.stringify(that.data.cars)) //原数组
    console.log('需要', that.data.cars)
    for (let item of that.data.cars) {
      if (item.selected) {
        // delete item.goods.content
        console.log('过滤', item.goods)
        good.push(item)
        console.log(item)
        carts.push({
          gid: item.goods.id,
          id: item.id,
          num: item.num,
          price: item.goods.price,
          yunfei: item.yunfei,
          type: item.type
        })
      } else {
        good2.push(item)
      }
    }
    console.log('选中', good)
    good = JSON.stringify(good)
    carts = JSON.stringify(carts)
    // 获取的计算总价
    wx.request({
      url: app.globalData.api + "getcarttotal",                                                                                                                                                                                             
      data: {
        uid: that.data.uid,
        // level: that.data.level,
        carts: carts,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      success: function(res) {
        console.log('总价', res)
        console.log(res.data.price)
        let bean = res.data.bean
        that.setData({
          bean: bean
        })
        wx.navigateTo({
          url: '/pages/buynow/buynow?uid=' + that.data.uid + '&sid=' + that.data.sid + '&goods=' + good + '&total=' + res.data.total + '&price=' + res.data.price + '&yunfei=' + res.data.yunfei + '&bean=' + res.data.bean + '&car=' + car
        })
      },
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    wx.getStorage({
      key: 'userinfo',
      success: function(res) {
        that.setData({
          level: res.data.level,
         
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    wx.getStorage({
      key: 'userinfo',
      success: function(res) {
        console.log(res.data.id)
        that.setData({
          uid: res.data.id,
          sid: res.data.sid,
        })
        wx.request({
          url: app.globalData.api + "getcart",
          data: {
            uid: res.data.id,
            level: that.data.level
          },
          success: function(res) {
            console.log('加载购物车', res)
            let array = []
            res.data.list.map((item, index) => {
              array.push(Object.assign({}, item, {
                selected: true
              }))
            })
            console.log(array)
            that.setData({
              cars: array
            })
            wx.setStorage({
              key: 'carnum',
              data: res.data.list.length,
            })
            that.sum()
          },
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})